package com.icarsaas.saas.master.service;

import com.icarsaas.saas.common.enums.StatusEnum;
import com.icarsaas.saas.common.page.SoulPage;
import com.icarsaas.saas.master.model.MasterTenant;
import com.icarsaas.saas.master.repository.MasterTenantRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service
public class MasterTenantServiceImpl implements MasterTenantService {

    @Autowired MasterTenantRepository masterTenantRepo;
    @Override
    public MasterTenant findByTenantId(String tenantId) {
        return masterTenantRepo.findByTenantId(tenantId);
    }

    public MasterTenant get(Long id) {
        return masterTenantRepo.findById(id).orElse(null);
    }

    @Transactional(readOnly = false, value = "masterTransactionManager")
    public MasterTenant save(MasterTenant entity) {
        return masterTenantRepo.save(entity);
    }

    @Transactional(readOnly = false, value = "masterTransactionManager")
    public void delete(Long id) {
        masterTenantRepo.deleteById(id);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Transactional(value="masterTransactionManager")
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> ids) {
        return masterTenantRepo.updateStatus(statusEnum.getCode(), ids) > 0;
    }

    @Transactional(readOnly = true, value = "masterTransactionManager")
    public SoulPage<Map<String, Object>> listSoulData(SoulPage<Map<String, Object>> page, Map<String, Object> params) {
        StringBuffer sql = new StringBuffer("select t.* from master_tenant t where 1=1 ");
        if (params != null && params.size() > 0) {
            for (String key : params.keySet()) {
                String value = (String) params.get(key);
                if (StringUtils.isNotEmpty(value)) sql.append(" and t." + key + " like '%" + value + "%'");
            }
        }
        SoulPage<Map<String, Object>> pageResult = masterTenantRepo.findBySqlForSoul(page, sql.toString(), Map.class);
        return pageResult;
    }
}
